import {
  login,
  logout,
  getInfo,
  svs_get_config
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import {
  removeStore
} from "@/utils/storage"

import router, {
  resetRouter
} from '@/router'

const state = {
  token: getToken(),
  name: '',
  real_name: "",
  avatar: '',
  introduction: '',
  roles: [],
  appConfig: null,
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_REAL_NAME: (state, name) => {
    state.real_name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_APP_CONFIG: (state, config) => {
    state.appConfig = config;
  }
}

const actions = {
  // user login
<<<<<<< HEAD
  login({
    commit
  }, userInfo) {
    // const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login(userInfo).then(data => {
        // const {data} = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        // debugger
        resolve(data)
=======
  login({ commit }, userInfo) {
    // const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const {data} = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        // debugger
        resolve(response)
>>>>>>> 00985b19206a2c585f1c328e92bbe227e5fee301
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(data => {
        // console.log(data);
        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const {
          roles,
          name,
          avatar,
          introduction
        } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_REAL_NAME', data.real_name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        // 拿到userInfo中的权限表，以全局的store给到权限vuex module中。
        commit("permission/SET_PERMISSION", data.perm, {
          root: true
        })
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state,
    dispatch
  }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then((res) => {
        // console.log('logout',res);
<<<<<<< HEAD
        if (!res) { //服务器返回true，就是服务器清空了登录状态记录
          reject("未成功退出！")
=======
        if(!res.data){//服务器返回true，就是服务器清空了登录状态记录
          resolve()
>>>>>>> 00985b19206a2c585f1c328e92bbe227e5fee301
          return;
        }
        commit('SET_TOKEN', '')
        commit('SET_NAME', '')
        commit('SET_AVATAR', '')
        commit('SET_ROLES', [])
        // console.log("logout");
        removeToken()
        resetRouter()




        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, {
          root: true
        })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
<<<<<<< HEAD
      commit('SET_NAME', '')
      commit('SET_AVATAR', '')
=======
>>>>>>> 00985b19206a2c585f1c328e92bbe227e5fee301
      // console.log("resetToken");
      removeToken()
      resolve()
    })
  },

  // 获取app 配置。
  getAppConfig({
    commit
  }) {
    return svs_get_config().then(res => {
      commit('SET_APP_CONFIG', res)
    })
  }
  // dynamically modify permissions
  // async changeRoles({
  //   commit,
  //   dispatch
  // }, role) {
  //   const token = role + '-token'

  //   commit('SET_TOKEN', token)
  //   setToken(token)

  //   const {
  //     roles
  //   } = await dispatch('getInfo')

  //   resetRouter()

  //   // generate accessible routes map based on roles
  //   const accessRoutes = await dispatch('permission/generateRoutes', roles, {
  //     root: true
  //   })
  //   // dynamically add accessible routes
  //   router.addRoutes(accessRoutes)

  //   // reset visited views and cached views
  //   dispatch('tagsView/delAllViews', null, {
  //     root: true
  //   })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
